package com.xtkj.accountjava.controller;

import com.xtkj.accountjava.base.UnauthorizedException;
import com.xtkj.accountjava.entity.LogEntity;
import com.xtkj.accountjava.entity.UserAccountBookEntity;
import com.xtkj.accountjava.service.AccountBookService;
import com.xtkj.accountjava.service.LogService;
import com.xtkj.accountjava.service.impl.AccountBookServiceImpl;
import com.xtkj.accountjava.utils.MD5Utils;
import com.xtkj.accountjava.base.RequestEntity;
import com.xtkj.accountjava.base.Result;
import com.xtkj.accountjava.entity.UserEntity;
import com.xtkj.accountjava.service.UserService;
import com.xtkj.accountjava.utils.RSAUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    AccountBookService accountBookService;

    @Autowired
    LogService logService;

    @GetMapping("/getDate")
    public String getDate(){
        return  new Date().toString();
    }

    @PostMapping("/login")
    @Transactional(rollbackFor = Exception.class)
    public Result login(@RequestBody RequestEntity requestEntity){
        String requestEntityData = requestEntity.getData();
        UserEntity userEntity = RSAUtils.decryptStrToEntityData(requestEntityData, UserEntity.class);
        if(userEntity==null){
            return Result.error("操作失败",null) ;
        }

        String openid = userEntity.getOpenid();
        if(StringUtils.isEmpty(openid)){
            //验证账户名和密码
            String account = userEntity.getAccount();
            String password = userEntity.getPassword();
//            LoggerFactory.getLogger(this.getClass()).info("account="+account+",password="+password);
            //通过账户名查询人员
            UserEntity userByUserNameEntity = userService.findUserByUserAccount(account);
            if(userByUserNameEntity==null){
                return Result.error("该用户未注册",null) ;
            }else {
                String entityPassword = userByUserNameEntity.getPassword();
                if(password.trim().equalsIgnoreCase(entityPassword)){
                    //符合登录成功、更新token
                    String token = MD5Utils.getToken();
                    userByUserNameEntity.setModifyTime(new Date());
                    userByUserNameEntity.setToken(token);
                    UserEntity modifyUser = userService.modifyUser(userByUserNameEntity);
                    if(modifyUser==null){
                        return Result.error("登录失败",null) ;
                    }else {
                        LogEntity logEntity = new LogEntity();
                        logEntity.setCreateTime(new Date());
                        logEntity.setUserId(userEntity.getId());
                        logEntity.setOperCont("账号登录成功");
                        logEntity.setType(LogEntity.TYPE_LOGIN);
                        logService.saveLog(logEntity);
                        return Result.ok("登录成功",modifyUser) ;
                    }
                }else {
                    //
                    return Result.error("密码错误",null) ;
                }
            }
        }else {
            //不为空，查找数据库里面是否含有此人
            UserEntity userByOpenidEntity = userService.findUserByOpenid(openid);
            if(userByOpenidEntity==null){
                //没有此人则上传新建
                //检查用户名、密码
                //新人、新增
                userEntity.setCreateTime(new Date());
                //生成token
                userEntity.setToken(MD5Utils.getToken());

                UserEntity addUser = userService.addUser(userEntity);
                //设置默认账本
                UserAccountBookEntity userAccountBookEntity =
                        accountBookService.add_default_account_book(Integer.parseInt(addUser.getId() + ""));

                //设置默认账本id到个人信息
                HashMap<String, Object> objectHashMap = new HashMap<>();
                objectHashMap.put("userId",addUser.getId());
                objectHashMap.put("defAcbookId",userAccountBookEntity.getId().intValue());
                objectHashMap.put("defAcbookName",userAccountBookEntity.getAccountBookEntity().getName());
                UserEntity innerEditUser = userService.innerEditUser(objectHashMap);

                //将设置好的账本id赋值返回给前端
                addUser.setDefAcbookId(userAccountBookEntity.getId().intValue());
                addUser.setDefAcbookName(userAccountBookEntity.getAccountBookEntity().getName());

                if(addUser==null){
                    return Result.error("登录失败",null) ;
                }else {
                    //微信登录、新增
                    LogEntity logEntity = new LogEntity();
                    logEntity.setCreateTime(new Date());
                    logEntity.setUserId(addUser.getId());
                    logEntity.setOperCont("微信新增，登录成功");
                    logEntity.setType(LogEntity.TYPE_LOGIN);
                    logService.saveLog(logEntity);
                    return Result.ok("登录成功",addUser) ;
                }

            }else {
                //修改
//                userEntity.setId(userByOpenidEntity.getId());
                userByOpenidEntity.setModifyTime(new Date());
                //生成token
                userByOpenidEntity.setToken(MD5Utils.getToken());

                UserEntity modifyUser = userService.modifyUser(userByOpenidEntity);
                if(modifyUser==null){
                    return Result.error("登录失败",null) ;
                }else {

                    LogEntity logEntity = new LogEntity();
                    logEntity.setCreateTime(new Date());
                    logEntity.setUserId(modifyUser.getId());
                    logEntity.setOperCont("微信修改，登录成功");
                    logEntity.setType(LogEntity.TYPE_LOGIN);
                    logService.saveLog(logEntity);

                    return Result.ok("登录成功",modifyUser) ;
                }
            }
        }
    }

    @PostMapping("/edit/user")
    @Transactional(rollbackFor = Exception.class)
    public Result editUser(
            @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String token,
            @RequestParam Map<String,Object> requestMap
    ){
        UserEntity userEntity = userService.checkToken(token);
        if(userEntity==null){
            throw  new UnauthorizedException("登录过期");
        }
        String requestEntityData = (String) requestMap.get("data");
        HashMap<String,Object> parmsMap = RSAUtils.decryptStrToEntityData(requestEntityData, HashMap.class);

        //修改默认账本
        if(parmsMap!=null){
            if(parmsMap.get("name")!=null)userEntity.setName((String) parmsMap.get("name"));
            if(parmsMap.get("password")!=null)userEntity.setPassword((String) parmsMap.get("password"));
            if(parmsMap.get("avatar")!=null)userEntity.setAvatar((String) parmsMap.get("avatar"));
            if(parmsMap.get("dayBeanNum")!=null)userEntity.setDayBeanNum((int) parmsMap.get("dayBeanNum"));
            if(parmsMap.get("sumBeanNum")!=null)userEntity.setSumBeanNum((int) parmsMap.get("sumBeanNum"));
            if(parmsMap.get("modifyTime")!=null)userEntity.setModifyTime(new Date());
            if(parmsMap.get("sex")!=null)userEntity.setSex((int) parmsMap.get("sex"));
            if(parmsMap.get("province")!=null)userEntity.setProvince((String) parmsMap.get("province"));
            if(parmsMap.get("city")!=null)userEntity.setCity((String) parmsMap.get("city"));
            if(parmsMap.get("country")!=null)userEntity.setCountry((String) parmsMap.get("country"));
            if(parmsMap.get("defAcbookId")!=null)userEntity.setDefAcbookId((int) parmsMap.get("defAcbookId"));
            if(parmsMap.get("defAcbookName")!=null)userEntity.setDefAcbookName((String) parmsMap.get("defAcbookName"));
        }

        UserEntity modifyUser = userService.modifyUser(userEntity);
        if(modifyUser==null){
            return Result.error("修改失败",null) ;
        }
        return  Result.ok(modifyUser);
    }



    @PostMapping("/saveLog")
    @Transactional(rollbackFor = Exception.class)
    public Result saveLog(@RequestBody LogEntity logEntity){
        return  Result.ok(logService.saveLog(logEntity));
    }

    @GetMapping("/getUser/{id}")
    public Result getUserById(@PathVariable(name = "id") int id){

        return Result.ok(userService.findUserById(id)) ;
    }

}
